/**
 *  editShuttleBusInfo.html 页面的javascript文件
 */

$().ready(function () {

    // ---------判断用户信息是否失效---------
    isUserInfoNull();

    // ----------变量定义----------
    var $maxNum = $("#max-num");
    var $unlimited = $("#unlimited");
    var $limited = $("#limited");
    var $timeForenoon = $("#time-forenoon");
    var $timeAfternoon = $("#time-afternoon");
    var $timeForenoonDiv = $("#time-forenoon-div");
    var $timeAfternoonDiv = $("#time-afternoon-div");
    var $departureLocation = $("#departure-location");
    var $arriveLocation = $("#arrive-location");
    var $save = $("#save");
    var $driverTel = $("#driver-tel");
    var $driverName = $("#driver-name");
    var $departureDate = $("#departure-date");
    var $departureDateDiv = $("#departure-date-div"); // 班次日期所在的div层
    var vehicleDeliveryId = getUrlParam().vehicleDeliveryId; // 车辆派送id
    var departureTime;
    var departureLocation;
    var arriveLocation;
    var maxNum = 0; // 最大乘坐人数，0表示无限制
    var mapDriver = {};
    var driverName;
    var driverTel;
    var timeMark; // 用来确定时间段
    var driverId; // 司机编号

    // ----------报名人数限制处，两个按钮颜色切换----------
    $unlimited.on("click", function () {

        // 1. 去掉“自定义”按钮的颜色，并将输入框隐藏
        $limited.removeClass("my-button");
        $maxNum.hide();
        // 2. 为“无限制”按钮添加颜色
        $(this).addClass("my-button");
        // 3. 将maxNum 置为0
        $maxNum.val(0);
    });

    $limited.on("click", function () {

        // 1. 去掉“无限制”按钮样式
        $unlimited.removeClass("my-button");
        // 2. 给自己添加样式，并显示输入框
        $(this).addClass("my-button");
        $maxNum.show();

    });

    // ----------点击班次日期的提示----------
    $departureDateDiv.on("click", function () {

        // 提示用户
        $("#iosDialog1").show();
    });

    // ----------发车时间段选择----------
    // --上午
    //限定可选时间
    laydate.render({
        elem: '#time-forenoon'
        ,type: 'time'
        ,min: '09:00:00'
        ,max: '12:00:00'
        ,format: 'HH:mm'
        ,btns: ['clear', 'confirm']
    });
    $timeForenoonDiv.on("click", function () {

    });

    // --下午
    //限定可选时间
    laydate.render({
        elem: '#time-afternoon'
        ,type: 'time'
        ,min: '12:00:00'
        ,max: '18:00:00'
        ,format: 'HH:mm'
        ,btns: ['clear', 'confirm']
    });
    $timeAfternoonDiv.on("click", function () {

    });

    // ----------根据vehicleDeliveryId获取车辆派送信息----------
    $.get("/bcs/manage/getBaseInfoByVehicleDeliveryId?vehicleDeliveryId=" + vehicleDeliveryId,
        function (result) {
            if (result.manageResult.errcode === 0){
                console.log("获取成功");

                var targetData = result.manageResult.data;
                // 将获取的信息渲染到页面
                $departureDate.html(targetData.departureDate);
                if (targetData.maxNum === 0){
                    // 点亮“无限制”按钮
                    $unlimited.addClass("my-button");
                } else {
                    // 点亮“自定义按钮”，并显示限制人数
                    $limited.addClass("my-button");
                    $maxNum.val(targetData.maxNum);
                    $maxNum.show()
                }

                // 将时间渲染到input中
                timeMark = targetData.timeMark;
                if (timeMark === 1){
                    // 上午
                    $timeForenoon.text(targetData.departureTime);
                    // 添加样式
                    $timeForenoonDiv.addClass("my-color");
                } else {
                    // 下午
                    $timeAfternoon.text(targetData.departureTime);
                    // 添加样式
                    $timeAfternoonDiv.addClass("my-color");
                }
                $departureLocation.val(targetData.departureLocation);
                $arriveLocation.val(targetData.arriveLocation);

                // 将司机信息渲染到页面
                // driverId = targetData.driver_id;
                var driverList = targetData.driverInfoVoList;
                if (driverList !== null ){
                    var driverNameList = [];
                    var driverTelList = [];
                    for (var i=0; i<driverList.length; i++){
                        driverNameList.push(driverList[i].driverName);
                        driverTelList.push(driverList[i].driverTelephone)
                    }
                    $driverName.val(driverNameList.join(","));
                    $driverTel.val(driverTelList.join(","));
                }

            } else {
                console.log("获取失败")
            }
        });

    // ----------司机列表选择----------
    $.get("/bcs/manage/getDriverList", function (result) {
        console.log(result);
        if (result.manageResult.errcode === 0){
            console.log("获取成功");
            var targetData = result.manageResult.data;
            var driverList = [];
            for (var i=0; i<targetData.length; i++){
                var driverInfo = {"title" : targetData[i].driver_name, "value" : targetData[i].id}
                mapDriver[targetData[i].id] = targetData[i];
                driverList.push(driverInfo);
            }

            // 动态渲染复选列表
            $("#driver-name").select({
                title: "司机名称",
                multi: true,
                min:1,
                items: driverList,
                onChange:function(value){
                    console.log(value.values);
                    var valList = value.values.split(",");
                    console.log(valList);
                    var driverTelList = [];
                    if (value.values !== ""){
                        // 避免空值报错
                        for (var i=0; i<valList.length; i++){
                            console.log(valList[i]);
                            driverTelList.push(mapDriver[valList[i]]["driver_telephone"]);
                        }
                        $driverTel.val(driverTelList.join(","));
                    }else {
                        $driverTel.val("");
                    }
                },
                beforeClose: function (value) {
                    console.log(value);
                    var valList = value.split(",");
                    var driverTelList = [];
                    if (value !== ""){
                        // 避免空值报错
                        for (var i=0; i<valList.length; i++){
                            console.log(valList[i]);
                            driverTelList.push(mapDriver[valList[i]]["driver_telephone"]);
                        }
                        $driverTel.val(driverTelList.join(","));
                    }else {
                        $driverTel.val("");
                    }

                }
            });
        }
    });

    // ----------填写完表单后进行保存提交----------
    $save.on("click", function () {

        // 判断当前时间是处于在上午还是下午
        if (timeMark === 1){
            console.log("现在是上午");
            departureTime = $timeForenoon.text()
        } else {
            console.log("现在是下午");
            departureTime = $timeAfternoon.text()
        }

        // 起始/目标地点
        departureLocation = $departureLocation.val();
        arriveLocation = $arriveLocation.val();
        console.log(departureLocation + arriveLocation);

        if ($limited.hasClass("my-button")) {
            // 获取最大人数 并 判断是否合格
            maxNum = $maxNum.val();
            var iMaxNum = parseInt(maxNum); //如果变量val是字符类型的数则转换为int类型 如果不是则ival为NaN
            if (!isNaN(iMaxNum)){
                // 是合法数
                if(iMaxNum > 500){
                    $("#dialog .weui-dialog__bd").html("您输入的人数大于院内总人数啦！");
                    $("#dialog").show();
                    return;
                }
            } else {
                // 提示输入合法数
                $("#dialog .weui-dialog__bd").html("请您输入数字哦！");
                $("#dialog").show();
                return;
            }
        }

        if ($driverTel.val() === "" || $("#driver-name").val() === "") {
            // 提示用户，司机姓名或者手机为选择
            $("#dialog .weui-dialog__bd").html("您还没有选择司机哦！");
            $("#dialog").show();
            // return ;
        } else {
            // 弹出提示页面
            $("#iosDialog").show();
        }

    });


    // ----------提示框的点击事件----------
    // --提交确认，取消按钮
    $("#no").on('click', function () {
        $("#iosDialog").hide();
    });
    $("#yes").on('click', function () {
        $("#iosDialog").hide();
        $("#toast1").fadeIn(100);
        postEditInfo();
    });
    // --班次更改确定，取消按钮
    $("#no1").on("click", function () {
        $("#iosDialog1").hide();
    });
    $("#yes1").on("click", function () {
        $("#iosDialog1").hide();
        window.location.href = "../index.html";
    });

    // --知道了按钮
    $("#iknow").on("click", function () {
        $("#dialog").hide();
    });

    // ----------漏填提示----------
    function dialog(){
        $("#dialog .weui-dialog__bd").html("您还没有选择司机哦！");
        $("#dialog").show();
    }

    // ----------提交信息----------
    function postEditInfo() {
        console.log("maxNum " + maxNum);
        console.log("departureDate " + $departureDate.text());
        console.log("departureTime " + departureTime);
        console.log("departureLocation " + departureLocation);
        console.log("arriveLocation " + arriveLocation);
        console.log("driverName " + driverName);
        console.log("driverTel " + driverTel);
        console.log("id " + vehicleDeliveryId);
        console.log("timeMark " + timeMark);

        // 更新操作
        $.post("/bcs/manage/update", {
            'maxNum' : maxNum,
            'departureDate' : $departureDate.text(),
            'departureTime' : departureTime,
            'departureLocation' : departureLocation,
            'arriveLocation' : arriveLocation,
            'driverName' : $driverName.val(),
            'driverTel' : $driverTel.val(),
            'timeMark' : timeMark,
            'id' : vehicleDeliveryId
        }, function (result) {
            $("#toast1").fadeOut(100);
            if (result.manageResult.errcode === 0) {
                // 添加成功
                console.log('添加成功');
                $("#toast").fadeIn(100);
                setTimeout(function(){
                    $("#toast").fadeOut(100);
                }, 2000);
                // 跳往首页
                window.location.href = '../index.html?vehicleDeliveryId=' + vehicleDeliveryId;
            }else {
                // 添加失败
                console.log('添加失败')
            }
        }, "json");
    }

    // ----------判断用户是否失效---------
    function isUserInfoNull() {
        $.get("/bcs/user/isUserInfoNull", function (result) {

            if (result.bookResult.errcode === 1){
                // 用户信息已失效, 直接跳转
                $("#loadingToast .weui-toast__content").text("登录已过期,正在登录中");
                $("#loadingToast").fadeIn(100);
                // 使用微信oauth 的回调链接方式，进行再次登录
                window.location.href = result.bookResult.data;
            }
        });
    }

    // ----------获取url中的参数----------
    function getUrlParam() {
        var url = window.location.href;
        console.log(url);
        if(url.indexOf("?") === -1) return;
        var urlSplit = url.split("?")[1];
        var res = [];
        if(urlSplit.indexOf("&") === -1) {
            var arr1 = urlSplit.split("=");
            res[arr1[0]] = arr1[1]
        } else {
            var arr2 = urlSplit.split("&");
            for(var i = 0; i < arr2.length; i++) {
                var key = arr2[i].split("=");
                res[key[0]] = key[1]
            }
        }
        return res
    }
});